package com.lianxi.Courses.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lianxi.Courses.constant.DictConstant;
import com.lianxi.Courses.constant.UserConstant;
import com.lianxi.Courses.controller.UserController;
import com.lianxi.Courses.dao.GoldPointsMapper;
import com.lianxi.Courses.dao.UserMapper;
import com.lianxi.Courses.entity.GoldPoints;
import com.lianxi.Courses.entity.User;
import com.lianxi.Courses.entity.UserExample;
import com.lianxi.Courses.exception.*;
import com.lianxi.Courses.service.GoldPointsService;
import com.lianxi.Courses.service.UserService;
import com.lianxi.Courses.util.MD5Util;
import com.lianxi.Courses.util.ParameterUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Date;
import java.util.Map;


/**
 * 翔哥
 * 2025年10月11日
 */
@Service
@Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GoldPointsMapper goldPointsMapper;



    @Override
    public void register(User user) throws RequestParameterErrorException, UserErrorExcetion, MD5ErrorException {
        if (ParameterUtil.isNull(user.getLoginName()) || ParameterUtil.isNull(user.getPassword()) || ParameterUtil.isNull(user.getNickname())) {
            throw new RequestParameterErrorException("用户名、密码和昵称不能为空");
        }
        UserExample userExample = new UserExample();
        userExample.or().andLoginNameEqualTo(user.getLoginName());
        List<User> users = userMapper.selectByExample(userExample);
        if (!users.isEmpty()) {
            throw new UserErrorExcetion("该用户已存在");
        }
        user.setRole(UserConstant.NORMAL_STATE);
        user.setStatus(1);
        user.setCreateDate(new Date());
        user.setPassword(MD5Util.md5(user.getPassword()));
        userMapper.insert(user);
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public User login(String loginName, String password,String code ,String image) throws CodeErrorException, UserErrorExcetion, MD5ErrorException, RequestParameterErrorException, UserAdminErrorExcetion {
        if (ParameterUtil.isNull(loginName)||ParameterUtil.isNull(password)||ParameterUtil.isNull(image)){
            throw new RequestParameterErrorException("请填将信息填完整。");
        }
        if (!code.equals(image)) {
            throw new CodeErrorException("验证码错误");
        }

        UserExample userExample =new UserExample();
        userExample.or()
                .andLoginNameEqualTo(loginName)
                .andPasswordEqualTo(MD5Util.md5(password));

        List<User> users= userMapper.selectByExample(userExample);
        if (users.isEmpty()){
            throw new UserErrorExcetion("用户或密码错误");
        }
        UserExample userExample02 =new UserExample();
        userExample02.or()
                .andLoginNameEqualTo(loginName)
                .andPasswordEqualTo(MD5Util.md5(password))
                .andRoleEqualTo(UserConstant.ADMIN_STATE);
        List<User> users02= userMapper.selectByExample(userExample02);

        if(users02.isEmpty()){
            throw new UserAdminErrorExcetion("该管理员不存在");
        }
        User user =users02.get(0);
        return user;
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public PageInfo<User> findByParams(User userParam,String pageNo, String pageSize) {
        if (ParameterUtil.isNull(pageNo)) {
            pageNo = DictConstant.USER_DEFAULT_PAGE_NO;
        }
        if (ParameterUtil.isNull(pageSize)) {
            pageSize = DictConstant.USER_DEFAULT_PAGE_SIZE;
        }
        PageHelper.startPage(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
        List<User> users = userMapper.selectByParams(userParam);
        PageInfo<User> staffPage = new PageInfo<>(users);
        return staffPage;
    }

    @Override
    public User findById(String id) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)){
            throw new RequestParameterErrorException("请求参数有误");
        }

        return userMapper.selectByPrimaryKey(Integer.valueOf(id));
    }

    @Override
    public void updateUser(String id, String nickname, String role, String password, String email) throws RequestParameterErrorException, UserErrorExcetion {
        if(ParameterUtil.isNull(id)||ParameterUtil.isNull(nickname)||ParameterUtil.isNull(role)||ParameterUtil.isNull(email)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        if (!UserConstant.ADMIN_STATE.equals(role)&&!UserConstant.NORMAL_STATE.equals(role)){
            throw new UserErrorExcetion("角色有误");
        }
        User user = findById(id);
        if (!ParameterUtil.isNull(password)){
            user.setPassword(password);
        }
        System.out.println("昵称********************************"+nickname);
        user.setNickname(nickname);
        user.setRole(role);

        user.setEmail(email);
        userMapper.updateByPrimaryKeySelective(user);

    }

    @Override
    public void updateStatus(String id) throws RequestParameterErrorException {
        if (ParameterUtil.isNull(id)){
            throw new RequestParameterErrorException("请求参数有误");
        }
        User user =userMapper.selectByPrimaryKey(Integer.valueOf(id));

        System.out.println("1状态是*********************"+user.getStatus());
        if (UserConstant.USER_STATE_OPEN == user.getStatus()){
            user.setStatus(UserConstant.NORMAL_STATE_DOWN);
            userMapper.updateByPrimaryKeySelective(user);
        }else {
            user.setStatus(UserConstant.USER_STATE_OPEN);
            userMapper.updateByPrimaryKeySelective(user);
        }

    }

    @Override
    public void frontRegister(User user, String confirmPassword) throws RequestParameterErrorException, UserErrorExcetion, MD5ErrorException {
        if (ParameterUtil.isNull(user.getLoginName()) || ParameterUtil.isNull(user.getPassword())
                || ParameterUtil.isNull(user.getEmail()) || ParameterUtil.isNull(user.getNickname())) {
            throw new RequestParameterErrorException("用户名、密码、邮箱、昵称不能为空");
        }
        if (!user.getLoginName().matches("^[a-zA-Z0-9_]+$")) {
            throw new RequestParameterErrorException("登录名称只能由字母、数字和下划线组成");
        }
        if (user.getPassword().contains(" ") || user.getPassword().contains("/")) {
            throw new RequestParameterErrorException("密码不能包含空格和特殊字符'/'");
        }
        if (!user.getPassword().equals(confirmPassword)) {
            throw new RequestParameterErrorException("两次输入的密码不一致");
        }
        if (user.getNickname().length() > 50) {
            throw new RequestParameterErrorException("昵称长度不能超过50个字符");
        }
        if (!ParameterUtil.isValidEmail(user.getEmail())) {
            throw new RequestParameterErrorException("邮箱格式不正确");
        }
        UserExample loginNameExample = new UserExample();
        loginNameExample.or().andLoginNameEqualTo(user.getLoginName());
        List<User> loginNameUsers = userMapper.selectByExample(loginNameExample);
        if (!loginNameUsers.isEmpty()) {
            throw new UserErrorExcetion("该登录名称已存在");
        }
        UserExample emailExample = new UserExample();
        emailExample.or().andEmailEqualTo(user.getEmail());
        List<User> emailUsers = userMapper.selectByExample(emailExample);
        if (!emailUsers.isEmpty()) {
            throw new UserErrorExcetion("该邮箱已被注册");
        }
        user.setRole(UserConstant.NORMAL_STATE);
        user.setStatus(1);
        user.setCreateDate(new Date());
        user.setPassword(MD5Util.md5(user.getPassword()));
        userMapper.insert(user);
    }


    @Override
    public User frontLogin(String loginName, String password) throws UserErrorExcetion, MD5ErrorException, RequestParameterErrorException {
        if (ParameterUtil.isNull(loginName) || ParameterUtil.isNull(password)) {
            throw new RequestParameterErrorException("用户名和密码不能为空");
        }

        UserExample userExample = new UserExample();
        userExample.or()
                .andLoginNameEqualTo(loginName)
                .andPasswordEqualTo(MD5Util.md5(password));
        List<User> users = userMapper.selectByExample(userExample);

        if (users.isEmpty()) {
            throw new UserErrorExcetion("用户名或密码错误");
        }
        User user = users.get(0);
        if (user.getStatus() != UserConstant.USER_STATE_OPEN) {
            throw new UserErrorExcetion("用户已被禁用");
        }
        if (!UserConstant.NORMAL_STATE.equals(user.getRole())) {
            throw new UserErrorExcetion("非普通用户无法在此登录");
        }

        return user;
    }

    @Override
    public void UserInformationUpdate(String id, String oldPassword, String newPassword, String confirmPassword, String nickname, String email) throws RequestParameterErrorException, UserErrorExcetion, MD5ErrorException {

        if(ParameterUtil.isNull(id) || ParameterUtil.isNull(nickname) || ParameterUtil.isNull(email)){
            throw new RequestParameterErrorException("请求参数有误");
        }


        if (!nickname.matches("^[\u4e00-\u9fa5a-zA-Z0-9_]+$")) {
            throw new RequestParameterErrorException("昵称只能包含中文、字母、数字和下划线");
        }


        if (!ParameterUtil.isValidEmail(email)) {
            throw new RequestParameterErrorException("邮箱格式不正确");
        }

        User user = findById(id);

        if (!user.getEmail().equals(email)) {
            UserExample emailExample = new UserExample();
            emailExample.or().andEmailEqualTo(email);
            List<User> emailUsers = userMapper.selectByExample(emailExample);
            if (!emailUsers.isEmpty()) {
                throw new UserErrorExcetion("该邮箱已被注册");
            }
        }

        if(!ParameterUtil.isNull(newPassword)){
            if(ParameterUtil.isNull(oldPassword)){
                throw new RequestParameterErrorException("修改密码时必须提供旧密码");
            }
            if(ParameterUtil.isNull(confirmPassword)){
                throw new RequestParameterErrorException("必须确认新密码");
            }
            if(!MD5Util.md5(oldPassword).equals(user.getPassword())) {
                throw new UserErrorExcetion("旧密码不正确");
            }
            if(!newPassword.equals(confirmPassword)){
                throw new UserErrorExcetion("两次输入的新密码不一致");
            }


            user.setPassword(MD5Util.md5(newPassword));
        }

        user.setNickname(nickname);
        user.setEmail(email);
        userMapper.updateByPrimaryKeySelective(user);
    }




//    @Override
//    public void signIn(String userId) throws RequestParameterErrorException, UserErrorExcetion {
//        if (ParameterUtil.isNull(userId)) {
//            throw new RequestParameterErrorException("用户ID不能为空");
//        }
//
//        User user = findById(userId);
//        Date now = new Date();
//        Date today = new Date(now.getYear(), now.getMonth(), now.getDate());
//        String lastLoginDateStr = user.getLoginDate();
//
//        if (lastLoginDateStr != null && !lastLoginDateStr.isEmpty()) {
//            try {
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date lastLoginDate = sdf.parse(lastLoginDateStr);
//                Date lastSignDate = new Date(lastLoginDate.getYear(), lastLoginDate.getMonth(), lastLoginDate.getDate());
//
//                if (today.equals(lastSignDate)) {
//                    throw new UserErrorExcetion("今天已经签到过了");
//                }
//            } catch (ParseException e) {
//                throw new RuntimeException("日期格式错误", e);
//            }
//        }
//
//
//        user.setLoginDate(now);
//        userMapper.updateByPrimaryKeySelective(user);
//
//
//        GoldPoints goldPoints = new GoldPoints();
//        goldPoints.setUserId(Integer.parseInt(userId));
//        goldPoints.setPointCount(5);
//        goldPoints.setGoldCount(0);
//        goldPoints.setInfo("每日签到获得5积分");
//        goldPoints.setCreateDate(now);
//
//        goldPointsMapper.insertSelective(goldPoints);
//    }
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void signIn(String userId) throws RequestParameterErrorException, UserErrorExcetion {
    if (ParameterUtil.isNull(userId)) {
        throw new RequestParameterErrorException("用户ID不能为空");
    }

    User user = findById(userId);
    Date now = new Date();
    Date today = new Date(now.getYear(), now.getMonth(), now.getDate());
    String lastLoginDateStr = user.getLoginDate();

    if (lastLoginDateStr != null && !lastLoginDateStr.isEmpty()) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date lastLoginDate = sdf.parse(lastLoginDateStr);
            Date lastSignDate = new Date(lastLoginDate.getYear(), lastLoginDate.getMonth(), lastLoginDate.getDate());

            if (today.equals(lastSignDate)) {
                throw new UserErrorExcetion("今天已经签到过了");
            }
        } catch (ParseException e) {
            throw new RuntimeException("日期格式错误", e);
        }
    }

    // 更新用户登录日期
    user.setLoginDate(now);
    // 关键修改：增加用户积分
    user.setAllPoint(user.getAllPoint() + 5);
    userMapper.updateByPrimaryKeySelective(user);

    // 创建积分记录
    GoldPoints goldPoints = new GoldPoints();
    goldPoints.setUserId(Integer.parseInt(userId));
    goldPoints.setPointCount(5);
    goldPoints.setGoldCount(0);
    goldPoints.setInfo("每日签到获得5积分");
    goldPoints.setCreateDate(now);

    goldPointsMapper.insertSelective(goldPoints);
}










}
